<template>
  <view>
    <!-- 返回组件 -->
    <navTabrBack
      :navbackStyle="['padding-right: 20rpx']"
      :title="'登录'"
      :titleStyle="['padding: 0 28rpx;']"
      :backEvent="backEvent"
    ></navTabrBack>
    <!-- 正文容器 -->
    <view class="view">
      <view class="holleLogin">您好，欢迎登录！</view>
      <!-- <view class="register">请先到微信小程序登录绑定手机号即可浏览器登录！</view> -->

      <view class="loginFrom">
        <!-- <view class="fromTitle">手机号</view>
        <view class="uni-form-item uni-column inputGather">
          <input
            v-model="userInfoData.phoneNumber"
            class="uni-input loginInput"
            maxlength="11"
            placeholder-style="color: #B8C0C7;"
            placeholder="请输入手机号"
          />
          <view class="loginInfor">获取验证码</view>
          <view
            class="placeLogin"
            :style="userInfoData.phoneNumber.length != 0 ? 'color: #fff' : ''"
            >手机码输入错误</view
          >
        </view>

        <view class="fromTitle titleTop">短信验证码</view>
        <view class="uni-form-item uni-column inputGather">
          <input
            v-model="userInfoData.msgCode"
            class="uni-input loginInput"
            maxlength="11"
            placeholder-style="color: #B8C0C7;"
            placeholder="请输入验证码"
          />
          <view class="placeLogin1">验证码输入错误</view>
        </view>
        <button type="primary" class="loginBtn" @click="login(false)">登录</button> -->

        <view class="fromHr">
          <view class="solidHr"></view>
          <!-- <view class="elseLogin">其他登录方式</view> -->
          <view class="solidHr"></view>
        </view>
      </view>
      <view @click="getuserinfo">
        <button
          type="primary"
          class="loginBtn"
          open-type="getPhoneNumber"
          @getphonenumber="onGetPhoneNumber"
        >
          微信授权登录
        </button>
      </view>
    </view>
  </view>

  <!-- 提示信息弹窗 -->
  <uni-popup ref="message" type="message">
    <uni-popup-message
      type="error"
      message="登录失败！"
      :duration="2000"
    ></uni-popup-message>
  </uni-popup>
  <!-- 提示信息弹窗 -->
  <uni-popup ref="message1" type="message">
    <uni-popup-message
      type="error"
      message="请检查填写是否异常！"
      :duration="2000"
    ></uni-popup-message>
  </uni-popup>
  <!-- 提示信息弹窗 -->
  <uni-popup ref="message2" type="message">
    <uni-popup-message
      type="error"
      message="请检查当前微信是否绑定手机号！"
      :duration="2000"
    ></uni-popup-message>
  </uni-popup>
  <!-- 提示信息弹窗 -->
  <uni-popup ref="success" type="message">
    <uni-popup-message
      type="success"
      message="登录成功！"
      :duration="1000"
    ></uni-popup-message>
  </uni-popup>
  <!-- 提示信息弹窗 -->
  <uni-popup ref="success1" type="message">
    <uni-popup-message
      type="error"
      message="当前不属于微信环境，请使用手机号登录！"
      :duration="2000"
    ></uni-popup-message>
  </uni-popup>
</template>

<script setup>
import { ref, inject, reactive, toRefs } from "vue";
import { onLoad } from "@dcloudio/uni-app";
const $url = inject("$url");
let message = ref();
let message1 = ref();
let message2 = ref();
let success = ref();
let success1 = ref();
const data = reactive({
  type: null,
  userInfo: {},
  userInfoData: {
    phoneNumber: "",
    msgCode: "",
    nickName: "用户" + (Math.floor(Math.random()*Date.parse(new Date()))+"").slice(0,6),
    headerImg: [
      "/uploads/file/header01.png",
      "/uploads/file/header02.png",
      "/uploads/file/header03.png",
      "/uploads/file/header04.png",
      "/uploads/file/header05.png",
      "/uploads/file/header06.png",
    ][Math.floor(Math.random() * 6)],
    isPassed: 0,
  },
  imgList: [
    "/uploads/file/header01.png",
    "/uploads/file/header02.png",
    "/uploads/file/header03.png",
    "/uploads/file/header04.png",
    "/uploads/file/header05.png",
    "/uploads/file/header06.png",
  ],
});
let { userInfoData } = toRefs(data);
onLoad((item) => {
  data.type = item.type;
});
// onMounted(() => {
//   // 判断是否为小程序
//   if (uni.getSystemInfoSync().hostName === "WeChat") {
//     isWeixin.value = true;
//     // console.log(isWeixin.value, 555);
//   }
// });
// 返回首页
const backEvent = () => {
  uni.switchTab({
    url: "/pages/index/index",
  });
  // if (data.type == 0) {
  // } else {
  //   uni.navigateBack();
  // }
};
// message.value.open("warn");
const login = (bool = false, phone) => {
  if (bool) {
    console.log(data.userInfoData.nickName);
    data.userInfoData.phoneNumber = phone;
    data.userInfoData.isPassed = 1;
  } else {
    data.userInfoData.isPassed = 0;
  }
  // if (data.userInfoData.phoneNumber.length != 11) {
  //   return;
  // }
  uni.request({
    url: $url + `/base/phoneLogin`,
    method: "POST",
    timeout: 6000,
    data: data.userInfoData,
    fail: (err) => {
      console.log(err, "请求失败！");
    },
    success(code) {
      uni.request({
        url: $url + `/user/getUserInfo`,
        method: "GET",
        timeout: 6000,
        header: {
          "x-token": code.data.data.token,
        },
        fail: (err) => {
          console.log(err, "请求失败！");
        },
        success(res) {
          res.data.data.userInfo.token = code.data.data.token;
          uni.setStorage({
            key: "useInfo",
            data: res.data.data.userInfo,
            success: function () {
              setTimeout(() => {
                if (data.type != 1) {
                  uni.switchTab({
                    url: "/pages/index/index",
                  });
                } else {
                  uni.navigateBack({
                    fail: () => {
                      uni.switchTab({
                        url: "/pages/index/index",
                      });
                    },
                    success: () => {
                      let page = getCurrentPages().pop();
                      if (page) {
                        page.onLoad(page.options); //执行上个页面的方法
                      }
                    },
                  });
                }
              }, 1000);
            },
          });
        },
      });
    },
  });
  // uni.switchTab({
  //   url: "/pages/index/index",
  // });
};
// 获取用户信息
const getuserinfo = () => {
  wx.getUserProfile({
    desc: "用于完善客户资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    success: (res) => {
      console.log(res, "微信用户信息");
      if (!res.encryptedData || !res.iv) return false;
      data.userInfo = res.userInfo;
    },
  });
};
// 获取手机号
const onGetPhoneNumber = (e) => {
  console.log(e);
  if (e.target.errMsg == "getPhoneNumber:ok") {
    uni.request({
      url: $url + `/base/getPhoneNumber`,
      method: "POST",
      timeout: 6000,
      data: { code: e.detail.code },
      fail: (err) => {
        message2.value.open("warn");
      },
      success(res) {
        console.log(res, data.userInfo);
        wxLogin(res.data.data?.phoneNumber);
      },
    });
  }
};
// 微信登录
const wxLogin = (phone) => {
  // 判断是否为小程序
  if (uni.getSystemInfoSync().hostName != "WeChat") {
    success1.value.open("warn");
    return;
  }
  // session_key 已经失效，需要重新执行登录流程
  wx.login({
    success(code) {
      console.log(code);
      if (code) {
        //发起网络请求 发送code 接收用户信息
        uni.request({
          url: $url + "/base/openid",
          data: { code: code.code },
          method: "POST",
          timeout: 6000,
          fail: (err) => {
            console.log(err, "请求失败！");
          },
          success(res) {
            //发起网络请求 接收用户信息
            console.log(res.data.data,66666);
            uni.request({
              url: $url + "/base/wxLogin",
              data: {
                unionId: res.data.data?.unionid ? res.data.data.unionid : "54321",
                nickName: data.userInfo.nickName + (Math.floor(Math.random() * Date.parse(new Date())) + "").slice(0, 6),
                headerImg: data.imgList[Math.floor(Math.random() * 6)],
                phone: phone,
              },
              method: "POST",
              timeout: 6000,
              fail: (err) => {
                console.log(err, "请求失败！");
              },
              success(res) {
                success.value.open("success");
                let token = res.data.data.token;
                uni.request({
                  url: $url + `/user/getUserInfo`,
                  method: "GET",
                  timeout: 6000,
                  header: {
                    "x-token": res.data.data.token,
                  },
                  fail: (err) => {
                    console.log(err, "请求失败！");
                  },
                  success(res) {
                    res.data.data.userInfo.token = token;
                    uni.setStorage({
                      key: "useInfo",
                      data: res.data.data.userInfo,
                      success: function () {
                        setTimeout(() => {
                          uni.navigateBack({
                            fail: () => {
                              uni.switchTab({
                                url: "/pages/index/index",
                              });
                            },
                            success: () => {
                              let page = getCurrentPages().pop();
                              if (page) {
                                page.onLoad(page.options); //执行上个页面的方法
                              }
                            },
                          });
                        }, 1000);
                      },
                    });
                  },
                });
              },
            });
          },
        });
      } else {
        console.log("登录失败！" + res.errMsg);
        message.value.open("warn");
      }
    },
  });
};
</script>

<style scoped>
.view {
  padding: 0 73rpx 52rpx 79rpx;
}
.holleLogin {
  margin-top: 221rpx;
  font-size: 54rpx;
  font-weight: 600;
  color: #000000;
  line-height: 76rpx;
}
.register {
  margin-top: 5rpx;
  font-size: 25rpx;
  font-weight: 400;
  color: #b8c0c7;
  line-height: 36rpx;
}
.loginFrom {
  margin-top: 87rpx;
}
.fromTitle {
  font-size: 33rpx;
  font-weight: 700;
  color: #000000;
  line-height: 45rpx;
}
.inputGather {
  position: relative;
}
.loginInput {
  padding: 24rpx 0 20rpx 0;
  font-size: 29rpx;
  border-bottom: 2rpx solid #efefef;
}
.placeLogin {
  margin-top: 15rpx;
  font-size: 29rpx;
  font-weight: 400;
  color: #ff0000;
  line-height: 40rpx;
}
.placeLogin1 {
  margin-top: 15rpx;
  font-size: 29rpx;
  font-weight: 400;
  color: #ff0000;
  line-height: 40rpx;
  opacity: 0;
}
.loginInfor {
  position: absolute;
  right: 0;
  top: 34rpx;
  height: 27rpx;
  font-size: 25rpx;
  color: #b8c0c7;
}
.titleTop {
  margin-top: 50rpx;
}
.loginBtn {
  margin-top: 105rpx;
  height: 91rpx;
  line-height: 91rpx;
  background: #1677ff;
  border-radius: 45rpx;
  font-size: 33rpx;
}
.fromHr {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 80rpx;
}
.elseLogin {
  font-size: 25rpx;
  font-weight: 400;
  color: #b8c0c7;
}
.solidHr {
  width: 183rpx;
  border: 2rpx solid #efefef;
}
.wxloginBtn {
  margin-top: 70rpx;
  height: 91rpx;
  line-height: 91rpx;
  border-radius: 45rpx;
  border: 2rpx solid #999999;
  font-size: 33rpx;
  font-weight: 400;
  color: #999999;
  background-color: #fff;
}
</style>
